package org.scheduler4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.scheduler4j.util.DateUtil;

/**
 * define a day duration.
 * 
 * @author Eric
 * 
 */
public class DayDuration implements Duration {
	/**
	 * the start date of this duration
	 */
	private Day startDate;

	/**
	 * the end date of this duration
	 */
	private Day endDate;

	/**
	 * constructor with start and end date.
	 * 
	 * @param start
	 * @param end
	 */
	public DayDuration(Day start, Day end) {
		checkValid(start, end);
		this.startDate = start;
		this.endDate = end;
	}

	/**
	 * constructor with start and end date.
	 * 
	 * @param start
	 * @param end
	 */
	public DayDuration(Date start, Date end) {
		this(new Day(start), new Day(end));
	}

	/**
	 * constructor with start date and duration
	 * 
	 * @param start
	 * @param days
	 */
	public DayDuration(Date start, int days) {
		this(start, DateUtil.afterDays(start, days));
	}

	/**
	 * constructor with start date and duration
	 * 
	 * @param start
	 * @param days
	 */
	public DayDuration(Day day, int days) {
		this(day.toDate(), days);
	}

	protected DayDuration() {
	}

	private void checkValid(Day start, Day end) {
		if (start.isSameDay(end) || start.isAfter(end)) {
			throw new InvalidDurationException();
		}
	}

	/**
	 * the start date of this duration
	 * 
	 * @return the start date of this duration
	 */
	public Day getStartDate() {
		return startDate;
	}

	/**
	 * set the start date of this duration.
	 * 
	 * @param startDate
	 *            the start date of this duration
	 */
	public void setStartDate(Day startDate) {
		this.startDate = startDate;
	}

	/**
	 * the end date of this duration.
	 * 
	 * @return the end date of this duration.
	 */
	public Day getEndDate() {
		return endDate;
	}

	/**
	 * set the end date of this duration
	 * 
	 * @param endDate
	 *            the end date of this duration.
	 */
	public void setEndDate(Day endDate) {
		this.endDate = endDate;
	}

	@Override
	public List<Day> getDays() {
		List<Day> result = new ArrayList<Day>();
		Day day = startDate;
		result.add(day);
		while (!(day = day.tomorrow()).isSameDay(endDate)) {
			result.add(day);
		}
		result.add(day);
		return result;
	}
}
